package cn.virens.common.util.exception;

@SuppressWarnings("serial")
public class APIException extends RuntimeException implements APIExceptionInter {
    private String message;
    private String code;

    public APIException() {
        this.fillInStackTrace();
    }

    public APIException(String message) {
        this("ERROR", message);
    }

    public APIException(String code, String message) {
        this.fillInStackTrace();

        this.setMessage(message);
        this.setCode(code);
    }

    public APIException(Throwable cause) {
        this(c(cause), m(cause), cause);
    }

    public APIException(String message, Throwable cause) {
        this("ERROR", message, cause);
    }

    public APIException(String code, String message, Throwable cause) {
        this.fillInStackTrace();

        this.setMessage(message);
        this.setCause0(cause);
        this.setCode(code);
    }

    @Override
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    private void setCause0(Throwable cause) {
        this.initCause(cause);
    }

    private static String c(Throwable cause) {
        return ExceptionUtil.getCode(cause);
    }

    private static String m(Throwable cause) {
        return ExceptionUtil.getMessage(cause);
    }

    /**
     * 将任意异常包装成APIException异常
     *
     * @param cause 其他异常对象
     * @return APIException对象
     */
    public static APIException warp(Throwable cause) {
        return new APIException(cause);
    }

}
